<?php if(!defined('WDK_PATH')) exit('No direct script access allowed');
/**
 * @since 2011. 9. 30
 * @author kinuz
 */

class Hp_Uri implements ArrayAccess
{
	//--------------------------------------------------------------------------------------------//
	//	functions to implemet for ArrayAccess
	//--------------------------------------------------------------------------------------------//
	public final function offsetSet($offset, $value) {$this->{$offset} = $value;}
	public final function offsetExists($offset) {return isset($this->{$offset});}
	public final function offsetUnset($offset) {unset($this->{$offset});}
	public final function offsetGet($offset) {return isset($this->{$offset}) ? $this->{$offset} : null;}
	//--------------------------------------------------------------------------------------------//
	
	protected $request_uri;
	protected $app_path	= 'app';
	protected $path		= '/';
	protected $class	= '';
	protected $method	= 'index';
	protected $params	= array();
	protected $uri 		= array();
	protected $config	= array();
	
	function __construct()
	{
		$this->config	= Wdk::config();
		$this->__init();
	}
	
	public function __init()
	{
		$this->__detect_uri();
	}
	
	private function __detect_uri()
	{
		if(isset($_SERVER) && array_key_exists('REQUEST_URI', $_SERVER))
		{
			$url = parse_url($_SERVER['REQUEST_URI']);
			$this->request_uri = $url['path'];
			$uri = explode("/", substr($this->request_uri, 1));
			if($uri[count($uri)-1] == '') array_pop($uri);
			$this->uri = $uri;
			
			if(empty($this->uri) === false && $this->uri[0] == 'admin')
			{
				$this->app_path = array_shift($uri);
				array_shift($this->uri);
			}
			if(empty($uri) == true)
			{
				$this->class = $this->config['index_app'];
			}
			else
			{
				while($p = array_shift($uri))
				{
					$path = BASE_PATH.$this->app_path.$this->path.$this->class.'/'.$p.'/';
					if(is_dir($path) && file_exists($path.'_controller.php'))
					{
						if($this->class !='')
						{
							$this->path.= $this->class.'/';						
						}
						$this->class = $p;
					}
					else
					{
						array_unshift($uri, $p);
						break;
					}
				}
			}
			if($this->path === '/' && array_key_exists(1, $this->uri) && $this->uri[0] !== $this->class )
			{
				throw new PageNotFoundException("Page not found..");
			}
			if(file_exists(BASE_PATH.$this->app_path.$this->path.$this->class.'/_controller.php'))
			{
				require_once BASE_PATH.$this->app_path.$this->path.$this->class.'/_controller.php';
				if(isset($uri[0]))
				{
					if(method_exists($this->class, $uri[0]))
					{
						$this->method = array_shift($uri);
					}
				}
			}
			else
			{
				throw new ControllerFileNotExistException("Controller File does not exist in '{$this->app_path}{$this->path}'");
			}
			$this->params = $uri;
			if(isset($url['query']))
			{
				parse_str($url['query'], $query);
				$this->params = array_merge($this->params, $query);
			}
		}
	}
}